package com.compass.doctor.ui.prescription

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.LinearLayout
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
import androidx.appcompat.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.compass.doctor.R
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnCustomButtonClick
import com.compass.doctor.callback.OnCustomItemClick
import com.compass.doctor.callback.OnTemplateItemClick
import com.compass.doctor.databinding.ActivityPrescribeForChineseMedicineBinding
import com.compass.doctor.dialog.PrescriptionRecordDialog
import com.compass.doctor.dialog.TemplateDialog
import com.compass.doctor.ui.WebDetailActivity
import com.compass.doctor.ui.patient.adapter.PopupAdapter
import com.compass.doctor.ui.prescription.adapter.MedicineInventoryAdapter
import com.compass.doctor.ui.prescription.adapter.PrescriptionDiagnoseAdapter
import com.compass.doctor.ui.prescription.adapter.PrescriptionDrugAdapter
import com.compass.doctor.ui.prescription.viewmodel.PrescribeViewModel
import com.compass.framework.constant.CHAT_INFO
import com.compass.framework.constant.KEY_CONSULT_TYPE
import com.compass.framework.constant.KEY_DISEASE_CONTENT
import com.compass.framework.constant.KEY_DRUG_LIST
import com.compass.framework.constant.KEY_DRUG_TYPE
import com.compass.framework.constant.KEY_PATIENT_ID
import com.compass.framework.constant.REFRESH_MESSAGE
import com.compass.framework.constant.RX_DETAILS
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.ext.onClick
import com.compass.framework.ext.toBeanOrNull
import com.compass.framework.manager.DictionariesManager
import com.compass.framework.model.Diagnosis
import com.compass.framework.model.Dictionaries
import com.compass.framework.model.Drug
import com.compass.framework.model.PrescriptionInformation
import com.compass.framework.model.TemplateDetails
import com.compass.framework.toast.TipsToast
import com.compass.framework.utils.BigDecimalUtils
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.MoneyInputFilter
import com.compass.framework.utils.dpToPx
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.netease.yunxin.kit.corekit.im.model.UserInfo

/**
 * Description： 中药饮片处方
 * Date:2024/10/19 11:17
 */
class ChineseMedicinePrescriptionActivity :
    BaseVBActivity<ActivityPrescribeForChineseMedicineBinding>(),
    MedicineInventoryAdapter.OnMedicineTextChange {


    companion object {
        fun start(
            context: Context,
            userInfo: UserInfo,
            patientId: String,
            presentDiseaseContent: String?
        ) {
            val intent = Intent(context, ChineseMedicinePrescriptionActivity::class.java)
            intent.putExtra(CHAT_INFO, userInfo)
            intent.putExtra(KEY_PATIENT_ID, patientId)
            intent.putExtra(KEY_DISEASE_CONTENT, presentDiseaseContent)
            context.startActivity(intent)
        }
    }

    private val prescribeViewModel: PrescribeViewModel by viewModels()
    private var rxInformation: PrescriptionInformation = PrescriptionInformation()
    private var diagnosesList: ArrayList<Diagnosis> = ArrayList()
    private lateinit var prescriptionDiagnoseAdapter: PrescriptionDiagnoseAdapter
    private var drugList: ArrayList<Drug> = ArrayList()
    private lateinit var prescriptionDrugAdapter: MedicineInventoryAdapter

    private var drugType: Int = 2//药品类型
    private var requestType: Int = 1
    private var presentDiseaseContent: String? = null
    private lateinit var diagnosis: Diagnosis//接收传递过来的诊断数据
    private lateinit var patientId: String//患者ID
    private lateinit var userInfo: UserInfo//云信信息
    private var drugsCost = "0"
    private var diagnosisFee = "0.00"//诊金
    private var num: Int = 1//中药默认副数

    //诊断回调
    private val mActivityResultLauncherDiagnosis: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    diagnosis = intent.serializable(key = "diagnosis")!!
                    if (!isAdd(diagnosis)) {
                        diagnosesList.add(diagnosis)
                        prescriptionDiagnoseAdapter.setData(diagnosesList)
                    } else {
                        showToast("该诊断已添加")
                    }

                }
            }
        }

    //药品回调
    private val mActivityResultLauncherDrug: ActivityResultLauncher<Intent>? =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
            if (it.resultCode == RESULT_OK) {
                it.data?.let { intent ->
                    drugList = intent.serializable(KEY_DRUG_LIST)!!
                    prescriptionDrugAdapter.setData(drugList)
                    computationalCosts()

                }
            }
        }

    private var onCustomBottomClick: OnCustomButtonClick = object : OnCustomButtonClick {
        override fun onButtonCallBack(position: Int, msgType: String?) {
            val item = drugList[position]
            var num = item.num.toInt()
            when (msgType) {
                "MinusSign" -> {
                    if (num > 1) num--
                    item.num = num.toString()
                    prescriptionDrugAdapter.notifyItemChanged(position)
                    computationalCosts()
                }

                "plusSign" -> {
                    num++
                    item.num = num.toString()
                    prescriptionDrugAdapter.notifyItemChanged(position)
                    computationalCosts()
                }

                "delete" -> {
                    drugList.remove(drugList[position])
                    prescriptionDrugAdapter.setData(drugList)
                    computationalCosts()
                }
            }
        }
    }

    private var onDrugItemClick = object : OnTemplateItemClick {
        override fun onTemplateSelectCallBack(id: String?, type: String) {
            showLoading()
            when (type) {
                "2" -> {
                    prescribeViewModel.getTemplateDetails(id, type)
                }

                "1" -> {
                    prescribeViewModel.getPrescriptionDetails(id, type)
                }
            }


        }

    }

    override fun initView(savedInstanceState: Bundle?) {
        patientId = intent.serializable(KEY_PATIENT_ID)!!
        userInfo = intent.serializable(CHAT_INFO)!!
        presentDiseaseContent = intent.getStringExtra(KEY_DISEASE_CONTENT)
        mBinding.edtPresentDisease.setText(presentDiseaseContent)
        rxInformation.num = num
        initPopupWindow()
        prescriptionDiagnoseAdapter = PrescriptionDiagnoseAdapter()
        prescriptionDrugAdapter = MedicineInventoryAdapter()
        prescriptionDrugAdapter.setCustomBottomClick(onCustomBottomClick)
        prescriptionDrugAdapter.setOnMedicineTextChange(this)
        mBinding.rcyDiagnosis.apply {
            val layoutFelManager = FlexboxLayoutManager(context)
            layoutFelManager.flexWrap = FlexWrap.WRAP // 按正常方向换行
            layoutFelManager.flexDirection = FlexDirection.ROW // 水平方向
            layoutFelManager.justifyContent = JustifyContent.FLEX_START // 左对齐
            layoutManager = layoutFelManager
            adapter = prescriptionDiagnoseAdapter
        }
        mBinding.rcyDrugs.apply {
            itemAnimator?.changeDuration = 0
            layoutManager = LinearLayoutManager(this@ChineseMedicinePrescriptionActivity)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(top = dpToPx(1), bottom = dpToPx(1))
                setLastBottom(true)
                setFirstHeadMargin(true)
            })
            adapter = prescriptionDrugAdapter
        }

        val filterNumber = MoneyInputFilter()
        filterNumber.setMaxValue(999.99)
        filterNumber.setDecimalLength(2)
        mBinding.edtDiagnosis.filters = arrayOf(filterNumber)
        mBinding.edtDiagnosis.addTextChangedListener {
            var diagnosis = it.toString().trim()
            diagnosisFee = diagnosis.ifEmpty {
                "0.00"
            }
            diagnosisFee = BigDecimalUtils.add("0.00",diagnosisFee,2)
            rxInformation.diagnosisFee=diagnosisFee
            computationalCosts()
        }

    }

    override fun intListener() {
        mBinding.tvAddDiagnosis.onClick {
            requestType = 1
            val intent = Intent(this, DiagnoseActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, "1")
            mActivityResultLauncherDiagnosis?.launch(intent)
        }
        mBinding.tvAddDrugs.onClick {
            requestType = 3
            val intent = Intent(this, AddDrugActivity::class.java)
            intent.putExtra(KEY_CONSULT_TYPE, requestType)
            intent.putExtra(KEY_DRUG_TYPE, drugType)
            intent.putExtra(KEY_DRUG_LIST, drugList)
            mActivityResultLauncherDrug?.launch(intent)
        }
        mBinding.tvTemplate.onClick {
            TemplateDialog.Builder(this, onDrugItemClick).show()
        }
        mBinding.tvPrescriptionRecord.onClick {
            PrescriptionRecordDialog.Builder(this, 2, patientId, onDrugItemClick).show()
        }
        prescriptionDiagnoseAdapter.onItemClickListener = { _, position ->
            diagnosesList.remove(diagnosesList[position])
            prescriptionDiagnoseAdapter.setData(diagnosesList)
        }

        mBinding.edtPresentDisease.addTextChangedListener {
            it?.let {
                rxInformation.presentDisease = it.toString()
            }
        }
        mBinding.tvFrequency.onClick {
            initFrequency()
        }
        mBinding.tvUsage.onClick {
            initUsage()
        }
        mBinding.tvPreview.onClick {
            if (rxInformation.patientId.isEmpty()) {
                showToast("患者id不能为空")
                return@onClick
            }
            if (diagnosesList.isEmpty()) {
                showToast("请先选择临床诊断")
                return@onClick
            }
            if (drugList.isEmpty()) {
                showToast("请添加药品信息")
                return@onClick
            }
            if (rxInformation.usage.isNullOrEmpty()) {
                TipsToast.showTips("请选择药品用法")
                return@onClick
            }
            if (rxInformation.frequency.isNullOrEmpty()) {
                TipsToast.showTips("请选择给药频次")
                return@onClick
            }



            rxInformation.type = drugType
            rxInformation.drugs = drugList
            rxInformation.diagnosis = diagnosesList
            showLoading()
            prescribeViewModel.prescriptionCreate(rxInformation)


        }
        mBinding.tvMinusSign.onClick {
            if (num > 1) num--
            setDrugNumber()
        }
        mBinding.tvPlusSign.onClick {
            num += 3
            setDrugNumber()
        }

        popupAdapter.setOnCustomItemClick(object : OnCustomItemClick {
            override fun onItemCallBack(position: Int, value: String, label: String) {
                listPopupWindow.dismiss()
                when (windowType) {
                    1 -> {
                        rxInformation.frequency = value
                        mBinding.tvFrequency.text = label
                    }

                    2 -> {
                        rxInformation.usage = value
                        mBinding.tvUsage.text = label
                    }

                }
            }
        })
    }


    override fun initData() {
        rxInformation.patientId = patientId

        prescribeViewModel.createLiveData.observe(this) {
            dismissLoading()
            it?.let { id ->
                showToast("开方成功，等待药师审核后推送患者")
                WebDetailActivity.start(
                    context = this@ChineseMedicinePrescriptionActivity,
                    url = RX_DETAILS + id,
                    title = "处方详情"
                )
                LiveDataBus.get().with(REFRESH_MESSAGE).postValue(REFRESH_MESSAGE)
                finish()
            }
        }
        prescribeViewModel.templateDetailsLiveData.observe(this) {
            dismissLoading()
            setTemplateInfo(it)
        }
    }

    private fun isAdd(diagnosis: Diagnosis): Boolean {
        for (item in diagnosesList) {
            if (item.id == diagnosis.id) {
                return true
            }
        }
        return false
    }

    private fun setDrugNumber() {
        rxInformation.num = num
        mBinding.tvNum.text = num.toString()
        computationalCosts()
    }

    /**
     * 计算金额
     */
    private fun computationalCosts() {
        drugsCost = "0.00"
        var cost ="0.00"
        for (drug in drugList) {
            drug.price?.let {
                drugsCost = BigDecimalUtils.add(BigDecimalUtils.mul(drug.num, it, 2), drugsCost, 2)
            }
        }
        cost = BigDecimalUtils.mul(drugsCost, rxInformation.num, 2)
        cost = BigDecimalUtils.add(cost, diagnosisFee, 2)

        mBinding.tvDiagnosisCost.text = "￥$diagnosisFee"
        mBinding.tvAllCost.text = cost
        mBinding.tvPrescriptionCost.text = "￥$cost"
        mBinding.tvDrugsCost.text = "￥$drugsCost"
    }

    private var windowType = 0//弹出pop类型 1.给药频次  2.用法
    private lateinit var listPopupWindow: ListPopupWindow
    private lateinit var popupAdapter: PopupAdapter
    private fun initFrequency() {
        windowType = 1
        listPopupWindow.height = dpToPx(200)
        listPopupWindow.anchorView = mBinding.tvFrequency
        popupAdapter.setList(
            DictionariesManager.getPrescriptionFrequency()
                ?.toBeanOrNull<MutableList<Dictionaries>>()
        )
        LogUtil.e("给药频次==${DictionariesManager.getPrescriptionFrequency()}")
        listPopupWindow.show()

    }

    private fun initUsage() {
        windowType = 2
        listPopupWindow.height = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow.anchorView = mBinding.tvUsage
        popupAdapter.setList(
            DictionariesManager.getPrescriptionUsage()
                ?.toBeanOrNull<MutableList<Dictionaries>>()
        )
        LogUtil.e("药品用法==${DictionariesManager.getPrescriptionUsage()}")
        listPopupWindow.show()
    }


    private fun initPopupWindow() {
        listPopupWindow = ListPopupWindow(this)
        val bgDrawable = ContextCompat.getDrawable(
            this,
            R.drawable.ps_permission_desc_bg
        )
        listPopupWindow.setBackgroundDrawable(bgDrawable)
        popupAdapter = PopupAdapter(this)
        listPopupWindow.setAdapter(popupAdapter)
        listPopupWindow.width = LinearLayout.LayoutParams.WRAP_CONTENT
        listPopupWindow.isModal = true
    }

    /**
     * 设置模板信息
     */
    private fun setTemplateInfo(templateDetails: TemplateDetails?) {
        templateDetails?.let { details ->
            details.diagnosis?.let { list ->
                diagnosesList.clear()
                diagnosesList.addAll(list)
                prescriptionDiagnoseAdapter.setData(diagnosesList)
            }

            details.drugs?.let { drugs ->
                drugList.clear()
                drugList.addAll(drugs)
                prescriptionDrugAdapter.setData(drugList)
            }
            computationalCosts()
        }
    }

    override fun onGramChange() {
        computationalCosts()
    }
}